<template>
	<view>
		<view class="uni-header">
			<label>
				订单管理 / 订单监控
			</label>
		</view>
		<view class="always-order-box ">
			<view class="always-order-content">
				<view class="box_item">
					<view class="labelApp">
						今日有效订单
					</view>
					<label class="numberTitle">
						{{todayOrderCount}}
					</label>
				</view>

				<view class="box_item">
					<view class="labelApp">
						今日取消订单
					</view>
					<label class="numberTitle">
						{{todayCancelOrderCount}}
					</label>
				</view>


				<view class="box_item">
					<view class="labelApp">
						今日订单支付金额
					</view>
					<label class="numberTitle">{{(todayTotalPrice/100).toFixed(2)}}</label>
				</view>

				<view class="box_item">
					<view class="labelApp">
						订单总数
					</view>
					<label class="numberTitle">{{orderTotalCount}}</label>
				</view>
			</view>

			<uni-table class="" ref="table" :loading="loading" :emptyText="data.length || '暂无更多数据'" stripe>
				<!-- 表头行 -->
				<uni-tr>
					<uni-th align="center">
						<!-- 订单号 -->
					</uni-th>
					<uni-th align="center">
						<!-- 店铺 -->
					</uni-th>
					<uni-th align="left">
						<!-- 收货地址 -->
					</uni-th>
					<uni-th align="left">
						<!-- 订单金额 -->
					</uni-th>
					<uni-th align="left">
						<!-- 配送费 -->
					</uni-th>
					<uni-th align="left">
						<!-- 打包费 -->
					</uni-th>
					<uni-th align="left">
						<!-- 支付金额 -->
					</uni-th>
					<uni-th align="left">
						<!-- 支付状态 -->
					</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr v-for="(item,index) in data">
					<uni-td>
						{{item.order_no}}
					</uni-td>
					<uni-td align="center">
						<text class="numberTitle">
							{{item.shop_id[0].title}}
						</text>
					</uni-td>
					<uni-td>{{item.address.title}}</uni-td>
					<uni-td>
						￥{{(item.total_price/100).toFixed(2)}}
					</uni-td>
					<uni-td>
						￥{{(item.delivery_price/100).toFixed(2)}}
					</uni-td>
					<uni-td>￥{{(item.pack_price/100).toFixed(2)}}</uni-td>
					<uni-td>
						<text class="fontColorApp">
							￥{{(item.total_fee/100).toFixed(2)}}
						</text>
					</uni-td>

					<uni-td v-if="item.status.value==0" style="color:#ff3333">
						未支付
					</uni-td>
					<uni-td v-else-if="item.status.value==9" style="color:#ff3333">
						已取消
					</uni-td>
					<uni-td v-else style="color:#53c21d">
						已支付
					</uni-td>


				</uni-tr>
			</uni-table>

		</view>

	</view>
</template>


<style scoped lang="scss">
	.always-order-gundong {
		border-radius: 5px;
	}

	.box_item {
		padding: 10px 0 0 0;
		text-align: center;
		box-shadow: 0 1px 10px 0 #e8ece6;
		border-radius: 5px;

		label {
			font-size: 40px;
			line-height: 110px;
		}
	}

	.always-order-content {
		margin: 30px 0;
		padding: 10px 0;
		min-height: 100px;
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(255px, 1fr));
		column-gap: 30px;
		row-gap: 20px;

	}

	.always-order-box {
		padding: 0 30px;
	}
	.numberTitle{
		color:#00c296
	}
</style>

<script>
	import Util from "@/js_sdk/validator/util.js"
	import {
		areaPower
	} from "@/js_sdk/manage-area/manage.js";
	var App = getApp()
	export default {
		data() {
			return {
				data: [],
				todayOrderCount: 0, //今日订单总数
				todayTotalPrice: 0, //今日订单总金额
				orderTotalCount: 0, //订单总数
				orderTotalFee: 0, //订单总金额
				todayCancelOrderCount: 0, //取消订单总数

			}
		},
		onLoad() {

			//查询出今日订单
			this.todayOrder();
			//获取订单总数
			this.orderCount();
			//获取推送订单
			this.getpushOrder();
		},
		methods: {
			//获取推送订单
			getpushOrder() {
				var that = this;
				//获取推送结果
				uni.onPushMessage((res) => {
					var data = res.data;
					uni.showToast({
						title: data.content,
						duration: 2000,
						icon: 'none'
					});
					var orderNo = data.payload.order_no;
					var message = data.payload.message;
					// console.log('取消推送结果',message);
					if (message == 'cancelorder') {
						const db = uniCloud.database();
						const order = db.collection('orders').where({
							order_no: orderNo,
							'status.value': db.command.gt(0)
						}).getTemp({
							getOne: true
						});
						const shop = db.collection('shop').getTemp();
						//查询出订单信息
						db.collection(order, shop).get().then(result => {
							var orderResult = result.result.data[0];
							if (orderResult._id) {
								//今日订单总数加1
								that.todayOrderCount--;
								//总订单量加1
								that.orderTotalCount--;
								that.todayCancelOrderCount--;
								//今日销售额累加
								that.todayTotalPrice -= orderResult.total_fee;
								//总销售额累加
								that.orderTotalFee -= orderResult.total_fee;
								var addOrder = {
									order_no: orderResult.order_no,
									shop_id: orderResult.shop_id,
									address: orderResult.address,
									total_price: orderResult.total_price,
									delivery_price: orderResult.delivery_price,
									pack_price: orderResult.pack_price,
									total_fee: orderResult.total_fee,
									status: orderResult.status
								}

								that.data.unshift(addOrder);
								if (that.data.length > 10) {
									that.data.pop();
								}

							}
						});

					} else {

						//判断当前订单号是否已存在，不存在再执行
						const index = that.data.findIndex((ev) => {
							return ev.order_no == orderNo;
						});
						if (index == -1) {
							const db = uniCloud.database();
							const order = db.collection('orders').where({
								order_no: orderNo,
								'status.value': db.command.gt(0)
							}).getTemp({
								getOne: true
							});
							const shop = db.collection('shop').getTemp();
							//查询出订单信息
							db.collection(order, shop).get().then(result => {
								var orderResult = result.result.data[0];
								if (orderResult._id) {
									//今日订单总数加1
									that.todayOrderCount++;
									//总订单量加1
									that.orderTotalCount++;
									//今日销售额累加
									that.todayTotalPrice += orderResult.total_fee;
									//总销售额累加
									that.orderTotalFee += orderResult.total_fee;
									var addOrder = {
										order_no: orderResult.order_no,
										shop_id: orderResult.shop_id,
										address: orderResult.address,
										total_price: orderResult.total_price,
										delivery_price: orderResult.delivery_price,
										pack_price: orderResult.pack_price,
										total_fee: orderResult.total_fee,
										status: orderResult.status
									}

									that.data.unshift(addOrder);
									if (that.data.length > 10) {
										that.data.pop();
									}

								}
							});
						}

					}


				});
			},
			//获取订单总金额
			getOrderTotalFee() {
				var db = uniCloud.database();
				const $ = db.command.aggregate
				db.collection('orders')
					.aggregate()
					.group({
						_id: null,
						totalPrice: $.sum('$total_fee')
					})
					.end().then(res => {
						this.orderTotalFee = res.result.data[0].totalPrice;
					})
			},
			//获取订单总数
			async orderCount() {
				const db = uniCloud.database();
				// 查询订单总量
				const $ = db.command.aggregate
				const dbCmd = db.command
				const orderCountData = await db.collection('orders').aggregate()
					.lookup({
						from: 'shop',
						let: {shopId: "$shop_id",areaS: "05300103" },
						pipeline: $.pipeline()
						.match(dbCmd.expr(
								$.and([  $.eq(['$_id', '$$shopId']), ])
						))
						.done(),
						as: 'shopInfo'
					}).match({
						"status.value": {$gte: 2,$lte: 5},
						"shopInfo.area_all.value": dbCmd.in(areaPower()),
					})
					.count('count').end()
					if(orderCountData.result.data.length > 0){
						this.orderTotalCount = orderCountData.result.data[0].count
					}
			},
			//获取今日订单
			todayOrder() {
				var that = this;
				const nowTime = new Date();
				const today = nowTime.getFullYear() + '-' + (parseInt(nowTime.getMonth()) + 1) + '-' + nowTime.getDate();
				var db = uniCloud.database();

				let order = db.collection('orders').orderBy("create_date.time_stamp desc").getTemp()
				let shop = db.collection('shop').field("_id,title,tel,area_all").getTemp({
					getOne: true
				})

				db.collection(order, shop).where({
					"create_date.time_stamp": db.command.gt(Util.getDayTimestamps(0).startTime).and(db.command.lt(Util
						.getDayTimestamps(0).endTime)),
					"shop_id.area_all.value": db.command.in(areaPower()),
					"status.value": db.command.gte(1)
				}).get().then(res => {
					this.data = res.result.data;
					let data = res.result.data;
					for (var i = 0; i < data.length; i++) {
						if (data[i].status.value != 9) {
							this.todayTotalPrice += data[i].total_fee;
							that.todayOrderCount += 1
						}
						if (data[i].status.value == 9) {
							that.todayCancelOrderCount += 1;
						}
					}
				})
			}
		}
	}
</script>